package service.impl.v2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.client.utils.URLEncodedUtils;
import org.jdom.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.paypal.api.payments.Amount;
import com.paypal.api.payments.Links;
import com.paypal.api.payments.Payer;
import com.paypal.api.payments.Payment;
import com.paypal.api.payments.RedirectUrls;
import com.paypal.api.payments.Transaction;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;

import dao.v2.ConfigVOMapper;
import dao.v2.MemberCartVOMapper;
import dao.v2.OrderVOMapper;
import dao.v2.PayVOMapper;
import model.AddressVO;
import model.GoodStandardVO;
import model.LogBuyCashVO;
import model.LogEarnVO;
import model.LogOrder;
import model.LogPackageVO;
import model.LogTicketVO;
import model.MemberVO;
import model.OrderCaseVO;
import model.OrderGoodVO;
import model.OrderPayVO;
import model.OrderRefund;
import model.OrderVO;
import model.PackagePayVO;
import model.PackageVO;
import service.v2.MemberItemService;
import service.v2.MemberService;
import service.v2.PayService;
import service.v2.PushInterService;
import service.v2.PushService;
import service.v2.SplitService;
import util.ClientCustomSSL;
import util.ConfigUtil;
import util.IPUtil;
import util.MD5Util;
import util.OssUtil;
import util.PackageUtil;
import util.PayCommonUtil;
import util.PropertieUtil;
import util.XMLUtil;
@Service
public class PayServiceImpl implements PayService {

	@Autowired
	private PayVOMapper dao;
	
	@Autowired
	private OrderVOMapper orderVOMapper;
	
	@Autowired
	private MemberCartVOMapper memberCartVOMapper;
	
	@Autowired
	private SplitService splitService;
	
	@Autowired
	private MemberService memberService;
	
	@Autowired
	private MemberItemService memberItemService;
	@Autowired
	private PushService pushservice;
	@Autowired
	private PushInterService pushInterService;
	@Autowired
	private PushInterService  pushinterservice;
	@Autowired
	private ConfigVOMapper configDao;
	/**
	 * 支付宝退款
	 * @throws Exception 
	 * @throws Exception 
	 */
	public AlipayTradeRefundResponse alipayRefund(String out_trade_no, String out_refund_no, String total_fee,
			String refund_fee) throws Exception {
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
				ConfigUtil.ALIPAY_APP_ID, ConfigUtil.ALIPAY_APP_PRIVATE_KEY, "json", ConfigUtil.ALIPAY_CHARSET,
				ConfigUtil.ALIPAY_PUBLIC_KEY, "RSA2");

		AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
		AlipayTradeRefundModel model = new AlipayTradeRefundModel();
		model.setOutTradeNo(out_trade_no);
		model.setOutRequestNo(out_refund_no);
		
		model.setRefundAmount(refund_fee);
		request.setBizModel(model);
		
		AlipayTradeRefundResponse response = alipayClient.execute(request);

		if (response.isSuccess()) {
			System.out.println("调用成功");
			System.out.println(response.getOutTradeNo());
			System.out.println(response.getRefundFee());
		} else {
			System.out.println("调用失败");
		}
		return response;
	}
	
	/**
	 * 微信退款
	 * @throws Exception 
	 */
	public String wechatRefund(HttpServletRequest request,String out_trade_no, String out_refund_no, String total_fee, String refund_fee,String trade_type) throws Exception {
		SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
		if("APP".equals(trade_type)){
			parameters.put("appid", ConfigUtil.WECHAT_APPID);
			parameters.put("mch_id", ConfigUtil.WECHAT_MCH_ID);
		}else{
			parameters.put("appid", ConfigUtil.WECHAT_WEB_APPID);
			parameters.put("mch_id", ConfigUtil.WECHAT_WEB_MCH_ID);
		}
		
		parameters.put("nonce_str", PayCommonUtil.CreateNoncestr());
		parameters.put("out_refund_no", out_refund_no);
		parameters.put("out_trade_no", out_trade_no); // 订单id
																			// 唯一
		System.out.println(refund_fee);
		System.out.println(total_fee);
		
		parameters.put("refund_fee", refund_fee);
		parameters.put("total_fee", total_fee);
		parameters.put("transaction_id", "");

		Map<String, Object> resultMap = new HashMap<String, Object>();
		/*----2.根据package生成签名sign---- */
		String sign= "";
		if("APP".equals(trade_type)){
			 sign = PayCommonUtil.createSign("UTF-8", parameters);
		}else{
			sign = PayCommonUtil.createSignWeb("UTF-8", parameters);
		}

		parameters.put("sign", sign);
		String requestXML = PayCommonUtil.getRequestXml(parameters);
		String retur = ClientCustomSSL.Wechatrefund(request, requestXML,trade_type);
		System.out.println(retur);
		return retur;
	}
	
	/**
	 * 微信支付(APP)
	 */
	public Object wxPrePay(String no, String price, String body, HttpServletRequest request, String url) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println(df.format(new Date()));
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int price100 = new BigDecimal(price).multiply(new BigDecimal(100)).intValue();
		// 设置回调地址-获取当前的地址拼接回调地址
		String uri = request.getRequestURL().toString();
		/*String domain = uri.substring(0, uri.lastIndexOf("wxPrePay"));*/
		String domain = uri.substring(0, uri.lastIndexOf("pay"));
		// 生产环境
		String notify_url = domain + url;

		SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
		/*服务号帐号：fuwuhao@youmikeji.com  密码   gzym2017  
		服务号商户帐号：1486244382  密码 gzym2017          "公众号APPID
		 wx57db12fcab596532"
		毛续文
		密钥：b2770096e30730180b78ba0641b7467a*/
		String os = request.getHeader("OS");
		String member_id = request.getHeader("SECRET");
		String device = request.getHeader("DEVICE");
		String  webOpenId = request.getParameter("webOpenId");
		if("wechat".equals(os) || "web".equals(os)){
			parameters.put("appid", ConfigUtil.WECHAT_WEB_APPID);
			parameters.put("mch_id", ConfigUtil.WECHAT_WEB_MCH_ID);
		}else{
			parameters.put("appid", ConfigUtil.WECHAT_APPID);
			parameters.put("mch_id", ConfigUtil.WECHAT_MCH_ID);
		}
		
		parameters.put("nonce_str", PayCommonUtil.CreateNoncestr());
		parameters.put("body",body);
		parameters.put("out_trade_no", no); // 订单id 唯一
		parameters.put("fee_type", "CNY");
//		price100 = 1;//@@@@@@@@@@@@@@@@@@@@@@@@@@@@待修改价格@@@@@@@@@@@@@@@@@@@@@@@@@@@@
		parameters.put("total_fee", String.valueOf(price100));
		if("wechat".equals(os)){
			System.out.println("***********************************"+request.getParameter("m_ip"));
			System.out.println("***********************************"+ IPUtil.getIP(request));
			//新版
			if(request.getParameter("m_ip") == null){
				parameters.put("spbill_create_ip", IPUtil.getIP(request));
				//旧版
			}else{
				parameters.put("spbill_create_ip", request.getParameter("m_ip"));	
			}
		}else{
			parameters.put("spbill_create_ip", IPUtil.getIP(request));
		}
		
		parameters.put("notify_url", notify_url);
		if("wechat".equals(os)){
			if(webOpenId==null||"".equals(webOpenId)){
				parameters.put("openid", dao.getPushOpenId(member_id));
			}else{
				parameters.put("openid", webOpenId);
			}
			parameters.put("trade_type", "JSAPI");
			// 设置签名
			String sign = PayCommonUtil.createSignWeb("UTF-8", parameters);
			parameters.put("sign", sign);
		}else if("web".equals(os)){
			if("pc".equals(device)){
				parameters.put("trade_type", "NATIVE");
				// 设置签名
				String sign = PayCommonUtil.createSignWeb("UTF-8", parameters);
				parameters.put("sign", sign);
			}else if("mobile".equals(device)){
				parameters.put("trade_type", "MWEB");
				
				Map sceneInfo = new HashMap();
				Map h5_info = new HashMap();
				h5_info.put("type", "Wap");
				h5_info.put("wap_url", configDao.loadConfig("WECHAT_HOST"));
				h5_info.put("wap_name", body);
				sceneInfo.put("h5_info", h5_info);
				
				parameters.put("scene_info", JSON.toJSONString(sceneInfo));
				
				// 设置签名
				String sign = PayCommonUtil.createSignWeb("UTF-8", parameters);
				parameters.put("sign", sign);
			}
		}else{
			parameters.put("trade_type", "APP");
			// 设置签名
			String sign = PayCommonUtil.createSign("UTF-8", parameters);
			parameters.put("sign", sign);
		}
		
		
		// 封装请求参数结束
		String requestXML = PayCommonUtil.getRequestXml(parameters);
		 System.out.println("********************"+"\n" + requestXML);
		// 调用统一下单接口
		String result = PayCommonUtil.httpsRequest(ConfigUtil.WECHAT_UNIFIED_ORDER_URL, "POST", requestXML);
		 System.out.println("********************"+"\n" + result);
		try {
			/** 统一下单接口返回正常的prepay_id，再按签名规范重新生成签名后，将数据传输给APP。参与签名的字段名为appId，partnerId，prepayId，nonceStr，timeStamp，package。注意：package的值格式为Sign=WXPay **/
			Map<String, String> map = XMLUtil.doXMLParse(result);
			SortedMap<Object, Object> parameterMap2 = new TreeMap<Object, Object>();
			
			if("wechat".equals(os)){
				parameterMap2.put("appId", ConfigUtil.WECHAT_WEB_APPID);
				parameterMap2.put("timeStamp",
						"" + Long.parseLong(String.valueOf(System.currentTimeMillis()).toString().substring(0, 10)));
				parameterMap2.put("nonceStr", PayCommonUtil.CreateNoncestr());
				parameterMap2.put("package", "prepay_id="+map.get("prepay_id"));
				parameterMap2.put("signType", "MD5");
				String sign2 = PayCommonUtil.createSignWeb("UTF-8", parameterMap2);
				parameterMap2.put("paySign", sign2);
			}else if("web".equals(os)){
				if("pc".equals(device)){
					/*parameterMap2.put("appid", ConfigUtil.WECHAT_WEB_APPID);
					parameterMap2.put("mch_id", ConfigUtil.WECHAT_WEB_MCH_ID);
					parameterMap2.put("time_stamp",
							"" + Long.parseLong(String.valueOf(System.currentTimeMillis()).toString().substring(0, 10)));
					parameterMap2.put("nonce_str", PayCommonUtil.CreateNoncestr());
					parameterMap2.put("product_id", no);
					String sign2 = PayCommonUtil.createSignWeb("UTF-8", parameterMap2);
					parameterMap2.put("sign", sign2);*/
					parameterMap2.put("no", no);
					parameterMap2.put("code_url", map.get("code_url"));
				}else if("mobile".equals(device)){
					parameterMap2.put("pay_url", map.get("mweb_url"));
				}
				//app
			}else{
				parameterMap2.put("appid", ConfigUtil.WECHAT_APPID);
				parameterMap2.put("partnerid", ConfigUtil.WECHAT_MCH_ID);
				parameterMap2.put("prepayid", map.get("prepay_id"));
				parameterMap2.put("package", "Sign=WXPay");
				parameterMap2.put("noncestr", PayCommonUtil.CreateNoncestr());
				// 本来生成的时间戳是13位，但是ios必须是10位，所以截取了一下
				parameterMap2.put("timestamp",
						"" + Long.parseLong(String.valueOf(System.currentTimeMillis()).toString().substring(0, 10)));
					String sign2 = PayCommonUtil.createSign("UTF-8", parameterMap2);
					parameterMap2.put("sign", sign2);
			}
			
			resultMap.put("state", 200);
			resultMap.put("result", parameterMap2);
			resultMap.put("msg", "");
			resultMap.put("remark", "");
			System.out.println(df.format(new Date()));
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return resultMap;
	}
	/**
	 * 回调解析
	 * @throws IOException 
	 */
	public SortedMap<Object, Object> resolveWechatParam(HttpServletRequest request) throws Exception {
		
		InputStream inputStream;
		StringBuffer sb = new StringBuffer();
		inputStream = request.getInputStream();
		String s;
		BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
		while ((s = in.readLine()) != null) {
			sb.append(s);
		}
		in.close();
		inputStream.close();
		// 解析xml成map
		Map<String, String> m = new HashMap<String, String>();
		m = XMLUtil.doXMLParse(sb.toString());
		if(m == null){
			return null;
		}
		for (Object keyValue : m.keySet()) {
			System.out.println(keyValue + "=" + m.get(keyValue));
		}
		// 过滤空 设置 TreeMap
		SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
		Iterator it = m.keySet().iterator();
		while (it.hasNext()) {
			String parameter = (String) it.next();
			String parameterValue = m.get(parameter);

			String v = "";
			if (null != parameterValue) {
				v = parameterValue.trim();
			}
			packageParams.put(parameter, v);
		}
		
		return packageParams;
	}
	
	public String checkWechatParam(SortedMap<Object, Object> packageParams) {
		String mch_id = (String) packageParams.get("mch_id"); // 商户号
		String openid = (String) packageParams.get("openid"); // 用户标识
		String out_trade_no = (String) packageParams.get("out_trade_no"); // 商户订单号
		String total_fee = (String) packageParams.get("total_fee");
		String transaction_id = (String) packageParams.get("transaction_id"); // 微信支付订单号
		String trade_type = (String) packageParams.get("trade_type"); // 微信支付订单号
		
		// 判断签名是否正确
		String resXml = null;
		if("APP".equals(trade_type)){
			if (!PayCommonUtil.isTenpaySign("UTF-8", packageParams)) {
				resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
						+ "<return_msg><![CDATA[通知签名验证失败]]></return_msg>" + "</xml> ";
				System.out.println("通知签名验证失败");
				return resXml;
			}
		}else{
			if (!PayCommonUtil.isTenpaySignWeb("UTF-8", packageParams)) {
				resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
						+ "<return_msg><![CDATA[通知签名验证失败]]></return_msg>" + "</xml> ";
				System.out.println("通知签名验证失败");
				return resXml;
			}
		}
		
		if (!"SUCCESS".equals((String) packageParams.get("result_code"))) {
			System.out.println("支付失败,错误信息：" + packageParams.get("err_code"));
			resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
					+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
			return resXml;
		}
		if("APP".equals(trade_type)){
			if (!ConfigUtil.WECHAT_MCH_ID.equals(mch_id)) {
				 System.out.println("支付失败,错误信息：" + "参数错误");
				resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
						+ "<return_msg><![CDATA[参数错误]]></return_msg>" + "</xml> ";
				return resXml;
			}
		}else{
			if (!ConfigUtil.WECHAT_WEB_MCH_ID.equals(mch_id)) {
				 System.out.println("支付失败,错误信息：" + "参数错误");
				resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
						+ "<return_msg><![CDATA[参数错误]]></return_msg>" + "</xml> ";
				return resXml;
			}
		}
		
		
		return resXml;
	}
	public Object aliPrePay(String no, String price, String body, HttpServletRequest request, String url) throws Exception {
		
		String os = request.getHeader("OS");
		String device = request.getHeader("DEVICE");
		
		// 设置回调地址-获取当前的地址拼接回调地址
		String uri = request.getRequestURL().toString();
		/*String domain = uri.substring(0, uri.lastIndexOf("aliPrePay"));*/
		String domain = uri.substring(0, uri.lastIndexOf("pay"));
		// 生产环境
		String notify_url = domain + url;
		System.out.println("回调URL"+notify_url);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		// 实例化客户端
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
				ConfigUtil.ALIPAY_APP_ID, ConfigUtil.ALIPAY_APP_PRIVATE_KEY, "json", ConfigUtil.ALIPAY_CHARSET,
				ConfigUtil.ALIPAY_APP_PUBLIC_KEY, "RSA2");
		// 实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
		// SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
		if("web".equals(os)){
			String return_url = request.getParameter("return_url");
			if("mobile".equals(device)){
				AlipayTradeWapPayRequest aliRequest=new AlipayTradeWapPayRequest();
				AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
				model.setOutTradeNo(no);
				model.setSubject("友米科技");
			    model.setTotalAmount(price);
			    model.setBody(body);
			    model.setTimeoutExpress("60m");
			    model.setProductCode("QUICK_WAP_WAY");
			    aliRequest.setBizModel(model);
			    // 设置异步通知地址
			    aliRequest.setNotifyUrl(notify_url);
			    // 设置同步地址
			    aliRequest.setReturnUrl(return_url);   
			    return alipayClient.pageExecute(aliRequest).getBody();
			}else if("pc".equals(device)){
				AlipayTradePagePayRequest aliRequest = new AlipayTradePagePayRequest();
				AlipayTradePagePayModel model = new AlipayTradePagePayModel();
				aliRequest.setReturnUrl(return_url);
				aliRequest.setNotifyUrl(notify_url);
				model.setBody(body);
				model.setSubject("友米科技");
				model.setOutTradeNo(no);
				model.setTotalAmount(price);
				model.setTimeoutExpress("60m");
				model.setProductCode("FAST_INSTANT_TRADE_PAY");
				aliRequest.setBizModel(model);
				return alipayClient.pageExecute(aliRequest).getBody();
			}else{
				return null;
			}
		}else{
			AlipayTradeAppPayRequest aliRequest = new AlipayTradeAppPayRequest();
			AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
			model.setBody(body);
			model.setSubject("友米科技");
			model.setOutTradeNo(no);
			model.setTimeoutExpress("60m");
//		price = "0.01";//@@@@@@@@@@@@@@@@@@@@@@@@@@@@待修改价格@@@@@@@@@@@@@@@@@@@@@@@@@@@@
			model.setTotalAmount(price);
			model.setProductCode("QUICK_MSECURITY_PAY");
			aliRequest.setBizModel(model);
			aliRequest.setNotifyUrl(notify_url);
			try {
				// 这里和普通的接口调用不同，使用的是sdkExecute
				AlipayTradeAppPayResponse response = alipayClient.sdkExecute(aliRequest);
				System.out.println(response.getBody());// 就是orderString
				// 可以直接给客户端请求，无需再做处理。
				paramMap.put("sign", response.getBody());
			} catch (AlipayApiException e) {
				e.printStackTrace();
			}
			return PackageUtil.packageParams(200, "successs", paramMap, "");
		}
	}
	
	public Map<String, String> resolveAliParam(HttpServletRequest request) throws Exception {
		// 获取支付宝POST过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map requestParams = request.getParameterMap();
		if(requestParams == null || requestParams.size()==0){
			return null;
		}
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。
//			 valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		System.out.println(params.get("trade_status"));
		return params;
	}
	
	public boolean checkAliParam(Map<String, String> params)  {
		//切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
		//boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
		if(!"TRADE_SUCCESS".equals(params.get("trade_status"))&&!"TRADE_FINISHED".equals(params.get("trade_status"))){
			return false;
			
		}
		try {
				return AlipaySignature.rsaCheckV1(params, ConfigUtil.ALIPAY_PUBLIC_KEY, ConfigUtil.ALIPAY_CHARSET, "RSA2");
		} catch (AlipayApiException e) {
			e.printStackTrace();
			return false;
		}
	}
	public String genPayOrder(int type, String free_cash, String remark, int pay_type, String member_id) {
		return dao.genPayOrder(type, free_cash, remark ,pay_type, member_id);
	}
	public OrderPayVO getPayOrderByNo(String out_trade_no) {
		return dao.getPayOrderByNo(out_trade_no);
	}
	public int subFreeCash(String member_id, double price, String ticket, String rate, String country) {
		int re = dao.subFreeCash(member_id,  price);
		if(re == 1){
			//加入余额消费日志
			dao.insertCashOutLog6(member_id, price,  ticket,  rate, country);
		}
		return re;
	}
	public int subFreeCashEn(String member_id, double price, String ticket, String rate, String country) {
		int re = dao.subFreeCashEn(member_id,  price);
		if(re == 1){
			//加入余额消费日志
			dao.insertCashOutLog6(member_id, price,  ticket,  rate, country);
		}
		return re;
	}
	public String insertMemberTicket(OrderPayVO payVO,String member_id, String ticket, String rate, int pay_type,String partner_level, String country) throws Exception {
		//接收充值ID
		LogTicketVO logTicketVO = new LogTicketVO();
		//添加兑换券
		int re = dao.insertMemberTicket(member_id,  ticket,  rate, partner_level);
		if(re ==1){
			//体验结束
			dao.updateExp(member_id, PropertieUtil.loadPropertie("common_level"));
			//加入兑换券充值日志
			dao.insertTicketInLog(member_id, ticket,  rate, pay_type, payVO,logTicketVO, country);
			//增加兑换券充值总数
			dao.addHistoryTotalTicket(member_id, ticket);
			//检查升级
			dao.checkAndUpdateMemberLevel(member_id);
			//电子提货券购买推送 >>开始
			if("1".equals(country)){
				pushservice.pushMemberTicket(member_id,rate,ticket);
			}else{
				pushinterservice.pushMemberTicket(member_id,rate,ticket,country);
			}
			
			
			//end
		}
		if(payVO != null){
			//修改支付订单状态
			dao.updatePayOrderState(payVO);
		}
		return dao.getLogticketNoById(logTicketVO);
	}
	public void updatePayOrderParams(String no, String jsonString) {
		dao.updatePayOrderParams( no,  jsonString);
	}
	public void updOrderAfterPay(String state, String pay_type, String conn_pay_id, String[] order_id_list) {
		// TODO Auto-generated method stub
		dao.updOrderAfterPay(state,pay_type,conn_pay_id,order_id_list);
	}
	public void updatePayOrderState1(String state, String id) {
		// TODO Auto-generated method stub
		dao.updatePayOrderState1(state,id);
	}
	public void delOrderTimer(String[] order_id_list) {
		// TODO Auto-generated method stub
		dao.delOrderTimer(order_id_list);
	}

	public OrderRefund getOrderRefundBy(String refund_id) {
		// TODO Auto-generated method stub
		return dao.getOrderRefundBy(refund_id);
	}
	

	public LogPackageVO getLogPackageById(String id) {
		// TODO Auto-generated method stub
		return dao.getLogPackageById(id);
	}

	public LogPackageVO getLogPackageByNo(String no) {
		// TODO Auto-generated method stub
		return dao.getLogPackageByNo(no);
	}

	public void updLogPackage(LogPackageVO packageLog) {
		// TODO Auto-generated method stub
		dao.updLogPackage(packageLog);
	}

	public int getToTalPackageTicket(String package_id) {
		// TODO Auto-generated method stub
		return dao.getToTalPackageTicket(package_id);
	}

	public void addLogEarn(LogEarnVO log) {
		// TODO Auto-generated method stub
		dao.addLogEarn(log);
	}

	public void addLogBuyCash(LogBuyCashVO log) {
		// TODO Auto-generated method stub
		dao.addLogBuyCash(log);
	}

	public int getToTalPackageAward(String package_id) {
		// TODO Auto-generated method stub
		return dao.getToTalPackageAward(package_id);
	}

	public int chetckOrderState(String[] order_id_list) {
		// TODO Auto-generated method stub
		return dao.chetckOrderState(order_id_list);
	}

	public void addPackagePay(PackagePayVO packPay) {
		// TODO Auto-generated method stub
		dao.addPackagePay(packPay);
	}

	public PackagePayVO getPackagePay(String id) {
		// TODO Auto-generated method stub
		return dao.getPackagePay(id);
	}

	public PackagePayVO getPackagePayByNo(String no) {
		// TODO Auto-generated method stub
		return dao.getPackagePayByNo(no);
	}
	
	public int updateOrderPayFinish(OrderPayVO payVO) {
		return dao.updateOrderPayFinish( payVO);
	}
	
	public int checkPackage(String package_id,String standard_id){
		return dao.checkPackage(package_id,standard_id);
	}
	
	public Map<String, Object> insertPackage(PackageVO pack,MemberVO member,AddressVO addressVO,String pay_type,String conn_pay_id,String order_from,String country){
		
		int count = memberCartVOMapper.updStandardNum(pack.getGood_standard_id(),"1");
		
		if(count==0){
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("state", "10909");
			map.put("msg", "库存不足");
			map.put("result", "");
			map.put("remark", "");
			return map; 
		}
		//扣余额
		
		
		int countUpdMoney = orderVOMapper.updMemberCash("3",pack.getPrice(),member.getId(),country);
		String level_str = orderVOMapper.getLevelStrByMemberId(member.getId());
		if(countUpdMoney>0){
			OrderVO order = new OrderVO();
			order.setOrder_from(order_from);
			order.setState("3");
			order.setTotal_sell_price(pack.getPrice());
			order.setTicket_status("0");
			order.setUse_ticket("N");
			order.setTotal_price(pack.getPrice());
			order.setTotal_ticket("0");
			order.setTotal_buy_cash("0");
			order.setCreate_by(member.getId());
			order.setPay_type("3");
			order.setAddress_tel(addressVO.getTel());
			order.setAddress_name(addressVO.getName());
			order.setAddress_content(addressVO.getCity()+" "+addressVO.getAddress());
			order.setFreight("0");
			order.setOrder_type("1");
			order.setJoin_cash(pack.getJoin_cash());
			order.setEvaluate("N");
			order.setConn_pay_id(conn_pay_id);
			order.setAddress_id(addressVO.getCity_id());
			order.setEnterprise_id(pack.getEnterprise_id());
			order.setBuy_sale("0");
			order.setCountry(country);
			order.setLevel_str(level_str);
			order.setAddress_obj_en(addressVO.getAddress_obj_en());
			//会员折扣率
			double member_rate = orderVOMapper.getDepositRate(member.getId());
			order.setMember_rate(String.valueOf(member_rate));
			
			memberCartVOMapper.InsertOrder(order);	
			order = orderVOMapper.getOrderById(order.getId());
			
			OrderCaseVO orderCase = new OrderCaseVO();
			orderCase.setOrder_id(order.getId());
			orderCase.setCase_no("1");
			orderCase.setState("3");
			
			orderVOMapper.insertOrderCase(orderCase);
			String case_id = orderCase.getId();
			
			List<GoodStandardVO> goodStandardList  = memberCartVOMapper.getGoodStandardListById(new String[]{pack.getGood_standard_id()});
			OrderGoodVO ordergood = new OrderGoodVO();
			ordergood.setOrder_id(order.getId());
			ordergood.setCase_id(case_id);
			ordergood.setGood_id(goodStandardList.get(0).getGood_id());
			ordergood.setNum("1");
			ordergood.setGood_standard_id(pack.getGood_standard_id());
			ordergood.setGood_name(goodStandardList.get(0).getGood_name());
			ordergood.setStandard_name(goodStandardList.get(0).getTitle());
			ordergood.setTicket("0");
			ordergood.setPrice(goodStandardList.get(0).getSell_price());		
			ordergood.setSell_price(goodStandardList.get(0).getSell_price());
			ordergood.setCompany_id(pack.getCompany_id());
			String path = "Upload/order/"+order.getId()+"/";
			String file_name  = OssUtil.copyFile(goodStandardList.get(0).getImg(),path);
			ordergood.setImg(file_name);
			ordergood.setStandard_no(goodStandardList.get(0).getNo());
			memberCartVOMapper.addOrderGood(ordergood);
		
			LogOrder log_ord = new LogOrder();
			log_ord.setOrder_id(order.getId());
			log_ord.setMember_id(member.getId());
			log_ord.setRemark("【套餐】已生成");
			orderVOMapper.InsertLogOrder(log_ord);
			
			LogEarnVO logearn  = new LogEarnVO();
			logearn.setMember_id(member.getId());
			logearn.setType("5");
			logearn.setState("2");
			logearn.setBill_type("1");
			logearn.setRemark("在线商城套餐支付");
			logearn.setFree_cash(order.getTotal_price());
			logearn.setRead_yn("N");
			logearn.setOrder_id(order.getId());
			logearn.setCountry(country);
			dao.addLogEarn(logearn);
			
			String total_ticket = "";
			total_ticket = orderVOMapper.getToTalStandardTicket(order.getId());
			
			try{
				//体验结束
				dao.updateExp(member.getId(),PropertieUtil.loadPropertie("common_level"));
				
				if(Integer.parseInt(total_ticket)>0){
					splitService.split(member.getId(), member.getLevel(), 3, total_ticket, order.getMember_rate(), order.getId(), order.getJoin_cash(), null,null);
				}
				else if(Integer.parseInt(total_ticket)==0&&Double.parseDouble(order.getJoin_cash())>0){	
					splitService.splitJoinAward(member.getId(), member.getLevel(), 3, total_ticket,
							order.getMember_rate(), order.getId(), order.getJoin_cash(), null);
				}
				//买套餐分润推送  东西 
				if("1".equals(order.getCountry())){
					pushservice.BuyGoodsPackageProfitByOrderId(order.getId());	
					pushservice.pushOrderPayOne(order.getId());
				}else{
					pushInterService.BuyGoodsPackageProfitByOrderId(order.getId(),order.getCountry());
					pushInterService.pushOrderPayOne(order.getId(),order.getCountry());
				}
				
			//	memberService.updMemberLevel(member.getId(),PropertieUtil.loadPropertie("vip_level"),PropertieUtil.loadPropertie("common_level"),PropertieUtil.loadPropertie("primary_level"));
			int  updCount = dao.updMemberLevel(member.getId(),PropertieUtil.loadPropertie("vip_level"),PropertieUtil.loadPropertie("common_level"),PropertieUtil.loadPropertie("primary_level"));
			if(updCount>0){
				dao.saveMembeLevelLogs(member.getId(),member.getLevel(),PropertieUtil.loadPropertie("primary_level"));
			}
				if(Double.parseDouble(pack.getRecharge_ticket())>0){
					
					String rate = "";
					if(PropertieUtil.loadPropertie("vip_level").equals(member.getLevel()) || PropertieUtil.loadPropertie("common_level").equals(member.getLevel())){
						rate = memberItemService.getRateByLevel(PropertieUtil.loadPropertie("primary_level"));
					}else{
						rate = memberItemService.getRateByLevel(member.getLevel());
					}
					
					String conn_no = insertMemberTicket(null, member.getId(), pack.getRecharge_ticket(), rate, Integer.parseInt(pay_type), PropertieUtil.loadPropertie("partner_level"),country);
					splitService.split(member.getId(), member.getLevel(), 1, pack.getRecharge_ticket(), rate, null, 0+"", pay_type+"",country);
					//买套餐分润推送 送券(充劵)
					
					if("1".equals(order.getCountry())){
						pushservice.BuyGoodsPackageProfitByConn_no(conn_no);	
					}else{
						pushInterService.BuyGoodsPackageProfitByConn_no(conn_no,order.getCountry());	
					}
				}
				
			}catch(Exception e){
				e.printStackTrace();
			}
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("state", "200");
		map.put("msg", "success");
		map.put("result", "");
		map.put("remark", "");
		//套餐的推送 余额支付的
		//order.getId()
		return map;
		}else {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("state", "10907");
			map.put("msg", "余额不足");
			map.put("result", "");
			map.put("remark", "");
			return map;
		}
	}
	public Map<String, Object> insertPackage1(PackageVO pack,MemberVO member,AddressVO addressVO,String pay_type,String conn_pay_id,OrderPayVO payVO,String order_from,String country){
		int count = memberCartVOMapper.updStandardNum(pack.getGood_standard_id(),"1");
		if(count==0){
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("state", "10909");
			map.put("msg", "库存不足");
			map.put("result", "");
			map.put("remark", "");
			return map; 
		}
			String level_str = orderVOMapper.getLevelStrByMemberId(member.getId());
			OrderVO order = new OrderVO();
			
			order.setOrder_from(order_from);
			order.setState("3");
			order.setTotal_sell_price(pack.getPrice());
			order.setTicket_status("0");
			order.setUse_ticket("N");
			order.setTotal_price(pack.getPrice());
			order.setTotal_ticket("0");
			order.setTotal_buy_cash("0");
			order.setCreate_by(member.getId());
			order.setPay_type(pay_type);
			order.setAddress_tel(addressVO.getTel());
			order.setAddress_name(addressVO.getName());
			order.setAddress_content(addressVO.getCity()+" "+addressVO.getAddress());
			order.setFreight("0");
			order.setOrder_type("1");
			order.setJoin_cash(pack.getJoin_cash());
			order.setEvaluate("N");
			order.setConn_pay_id(conn_pay_id);
			order.setAddress_id(addressVO.getCity_id());
			order.setEnterprise_id(pack.getEnterprise_id());
			order.setBuy_sale("0");
			order.setCountry(country);
			order.setLevel_str(level_str);
			order.setAddress_obj_en(addressVO.getAddress_obj_en());
			//会员折扣率
			double member_rate = orderVOMapper.getDepositRate(member.getId());
			order.setMember_rate(String.valueOf(member_rate));
			
			memberCartVOMapper.InsertOrder(order);	
			order = orderVOMapper.getOrderById(order.getId());
			
			OrderCaseVO orderCase = new OrderCaseVO();
			orderCase.setOrder_id(order.getId());
			orderCase.setCase_no("1");
			orderCase.setState("3");
			
			orderVOMapper.insertOrderCase(orderCase);
			String case_id = orderCase.getId();
			
			List<GoodStandardVO> goodStandardList  = memberCartVOMapper.getGoodStandardListById(new String[]{pack.getGood_standard_id()});
			OrderGoodVO ordergood = new OrderGoodVO();
			ordergood.setOrder_id(order.getId());
			ordergood.setCase_id(case_id);
			ordergood.setGood_id(goodStandardList.get(0).getGood_id());
			ordergood.setNum("1");
			ordergood.setGood_standard_id(pack.getGood_standard_id());
			ordergood.setGood_name(goodStandardList.get(0).getGood_name());
			ordergood.setStandard_name(goodStandardList.get(0).getTitle());
			ordergood.setTicket("0");
			ordergood.setPrice(goodStandardList.get(0).getSell_price());	
			ordergood.setSell_price(goodStandardList.get(0).getSell_price());
			ordergood.setCompany_id(pack.getCompany_id());
			String path = "Upload/order/"+order.getId()+"/";
			String file_name  = OssUtil.copyFile(goodStandardList.get(0).getImg(),path);
			ordergood.setImg(file_name);
			ordergood.setStandard_no(goodStandardList.get(0).getNo());
			
			memberCartVOMapper.addOrderGood(ordergood);
		
			LogOrder log_ord = new LogOrder();
			log_ord.setOrder_id(order.getId());
			log_ord.setMember_id(member.getId());
			log_ord.setRemark("【套餐】已生成");
			orderVOMapper.InsertLogOrder(log_ord);
			
			String total_ticket = "";
			total_ticket = orderVOMapper.getToTalStandardTicket(order.getId());
			try{
				
				//体验结束
				dao.updateExp(member.getId(),PropertieUtil.loadPropertie("common_level"));
				if(Integer.parseInt(total_ticket)>0){
					splitService.split(member.getId(), member.getLevel(), 3, total_ticket, order.getMember_rate(), order.getId(), order.getJoin_cash(), null,null);
				}
				else if(Integer.parseInt(total_ticket)==0&&Double.parseDouble(order.getJoin_cash())>0){	
					splitService.splitJoinAward(member.getId(), member.getLevel(), 3, total_ticket,
							order.getMember_rate(), order.getId(), order.getJoin_cash(), null);
				}
				//买东西分润推送
				//memberService.updMemberLevel(member.getId(),PropertieUtil.loadPropertie("vip_level"),PropertieUtil.loadPropertie("common_level"),PropertieUtil.loadPropertie("primary_level"));
				//买套餐分润推送
				if("1".equals(order.getCountry())){
					pushservice.BuyGoodsPackageProfitByOrderId(order.getId());	
					pushservice.pushOrderPayOne(order.getId());
				}else{
					pushInterService.BuyGoodsPackageProfitByOrderId(order.getId(),order.getCountry());
					pushInterService.pushOrderPayOne(order.getId(),order.getCountry());
				}

				int  updCount = dao.updMemberLevel(member.getId(),PropertieUtil.loadPropertie("vip_level"),PropertieUtil.loadPropertie("common_level"),PropertieUtil.loadPropertie("primary_level"));
				if(updCount>0){
					dao.saveMembeLevelLogs(member.getId(),member.getLevel(),PropertieUtil.loadPropertie("primary_level"));
				}
				
				if(Double.parseDouble(pack.getRecharge_ticket())>0){
					
					String rate = "";
					if(PropertieUtil.loadPropertie("vip_level").equals(member.getLevel()) || PropertieUtil.loadPropertie("common_level").equals(member.getLevel())){
						rate = memberItemService.getRateByLevel(PropertieUtil.loadPropertie("primary_level"));
					}else{
						rate = memberItemService.getRateByLevel(member.getLevel());
					}
					
					String conn_no = insertMemberTicket(payVO, member.getId(), pack.getRecharge_ticket(), rate, Integer.parseInt(payVO.getPay_type()), PropertieUtil.loadPropertie("partner_level"),country);
					splitService.split(member.getId(), member.getLevel(), 1, pack.getRecharge_ticket(), rate, conn_no, 0+"", payVO.getPay_type()+"",country);
					//买套餐分润推送
					if("1".equals(order.getCountry())){
						pushservice.BuyGoodsPackageProfitByConn_no(conn_no);	
					}else{
						pushInterService.BuyGoodsPackageProfitByConn_no(conn_no,order.getCountry());	
					}

				}

			}catch(Exception e){
				e.printStackTrace();
			}
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("state", "200");
		map.put("msg", "success");
		map.put("result", "");
		map.put("remark", "");
		
		return map;
	}
	
	public void shareBenifit(String[] order_id_List,MemberVO memberVO){
		List<OrderVO> orderList = orderVOMapper.getSimpleOrderByIdList(order_id_List);
		if(orderList!=null&&orderList.size()>0){
			for (int i = 0; i < orderList.size(); i++) {
				OrderVO oneOrder = orderList.get(i);
				String total_ticket = "";
				total_ticket = orderVOMapper.getToTalStandardTicket(oneOrder.getId());
				if(!"4".equals(oneOrder.getPay_type())){
					//没有使用兑换券
					if("0".equals(oneOrder.getTicket_status())){
						
						try{
							splitService.split(memberVO.getId(), memberVO.getLevel(), 2, total_ticket, oneOrder.getMember_rate(), oneOrder.getId(), oneOrder.getJoin_cash(), null,null);
							if(Integer.parseInt(total_ticket)==0&&Double.parseDouble(oneOrder.getJoin_cash())>0){	
								splitService.splitJoinAward(memberVO.getId(), memberVO.getLevel(), 2, total_ticket,
										oneOrder.getMember_rate(), oneOrder.getId(), oneOrder.getJoin_cash(), null);
							}
						}catch(Exception e){
							e.printStackTrace();
						}
					}
					//使用了兑换券
					else{
						if(Double.parseDouble(oneOrder.getJoin_cash())>0){	
							try {
								splitService.splitJoinAward(memberVO.getId(), memberVO.getLevel(), 2, total_ticket,
										oneOrder.getMember_rate(), oneOrder.getId(), oneOrder.getJoin_cash(), null);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
				}
			}
		}
	}
	
	@Override
	public Object payssionPrePay(String no, String price, String body, HttpServletRequest request, String url, String pay_key) {
//		var aa=md5('72b08351c18be48f'+'|'+'sofort'+'|'+'2.00'+'|'+'USD'+'|'+'123'+'|'+'82c67b72a7474dca975fd744fb6c190e')
		String sign = MD5Util.MD5Encode(ConfigUtil.PAYSSION_APIKEY + "|" + pay_key + "|" + price + "|" + "USD" + "|" + no + "|" + ConfigUtil.PAYSSION_SECRETKEY, "utf-8");
		Map map = new HashMap();
		map.put("sign", sign);
		map.put("url", url);
		map.put("api_key", ConfigUtil.PAYSSION_APIKEY);
		map.put("pm_id", pay_key);
		map.put("order_id", no);
		map.put("price", price);
		map.put("currency", "USD");
		dao.updatePayKey(no, pay_key);
		return PackageUtil.packageParams(200, "successs", map, "");
	}
	
	public static void main(String[] args) {
		String price = "10.001";
		System.out.println(new BigDecimal(price).multiply(new BigDecimal(100)).intValue());
	}

	public void updTest() {
		// TODO Auto-generated method stub
		String fr = dao.getTest();
		orderVOMapper.updTest();
	}
	
	@Override
	public Map<String, String> resolveAPayssionParam(HttpServletRequest request) {
		String transaction_id = request.getParameter("transaction_id");
		String pm_id = request.getParameter("pm_id");
		String state = request.getParameter("state");
		String amount = request.getParameter("amount");
		String currency = request.getParameter("currency");
		String order_id = request.getParameter("order_id");
		String notify_sig = request.getParameter("notify_sig");
		Map<String, String> map = new HashMap<String, String>();
		map.put("transaction_id", transaction_id);
		map.put("pm_id", pm_id);
		map.put("state", state);
		map.put("amount", amount);
		map.put("currency", currency);
		map.put("order_id", order_id);
		map.put("notify_sig", notify_sig);
		return map;
	}
	
	@Override
	public boolean checkPayssionParam(OrderPayVO payVO, Map<String, String> params) {
		try{
			JSONObject obj = (JSONObject) JSON.parse(payVO.getParams());
			String sign = MD5Util.MD5Encode(ConfigUtil.PAYSSION_APIKEY + "|" + obj.getString("payKey") + "|" +payVO.getTotal_price() +"|" + "USD" + "|" + payVO.getNo() +"|" + "completed" + "|" + ConfigUtil.PAYSSION_SECRETKEY , "utf-8");
			return params.get("notify_sig").equals(sign);
		}catch (Exception e) {
			return false;
		}
	}
	
	@Override
	public Object paypalPrePay(String no, String price, String body, HttpServletRequest request, String notify_url,
			String return_url, String cancel_url) throws PayPalRESTException {
		Payer payer = new Payer();
		payer.setPaymentMethod("paypal");
		Amount amount = new Amount();
		amount.setTotal(price);
		amount.setCurrency("USD");
		
		Transaction transaction = new Transaction();
		transaction.setAmount(amount);
		transaction.setNotifyUrl(configDao.loadConfig("HOST")+configDao.loadConfig("VERSION")+"/" + notify_url + "?order_id="+no);
		transaction.setDescription(body);
		List<Transaction> transactions = new ArrayList<Transaction>();
		transactions.add(transaction);
		
		
		RedirectUrls redirectUrls = new RedirectUrls();
		redirectUrls.setCancelUrl(cancel_url);
		redirectUrls.setReturnUrl(configDao.loadConfig("HOST")+configDao.loadConfig("VERSION")+"/pay/paypalReturnUrlNotify?returnUrl=" + URLEncoder.encode(return_url));
		
		Payment payment = new Payment();
		payment.setPayer(payer);
		payment.setTransactions(transactions);
		payment.setRedirectUrls(redirectUrls);
		payment.setIntent("sale");
		payment= payment.create(new APIContext(ConfigUtil.CLIENT_ID, ConfigUtil.CLIENT_SECRET, ConfigUtil.MODE));
		
		String href = "";
		for (Links links : payment.getLinks()) {
			if (links.getRel().equals("approval_url")) {
				href = links.getHref();// 客户付款登陆地址
			}
		}
		return PackageUtil.packageParams(200, "successs", href, "");
	}
	
	@Override
	public boolean checkPayPalParam(HttpServletRequest request) throws IOException {
		//从 PayPal 出读取 POST 信息同时添加变量„cmd‟  
	    Enumeration en = request.getParameterNames();  
	    String str = "cmd=_notify-validate";  
	    while (en.hasMoreElements()) {  
	        String paramName = (String) en.nextElement();  
	        String paramValue = request.getParameter(paramName);  
	        str = str + "&" + paramName + "="  
	                + URLEncoder.encode(paramValue, "utf-8");  
	        //此处的编码一定要和自己的网站编码一致，不然会出现乱码，paypal回复的通知为‘INVALID’  
	    }  
	    System.out.println("paypal#######:" + str);  
	    //建议在此将接受到的信息 str 记录到日志文件中以确认是否收到 IPN 信息  
	    //将信息 POST 回给 PayPal 进行验证  
	    //设置 HTTP 的头信息  
	    //在 Sandbox 情况下，设置：  
	    URL u = new URL("https://www.sandbox.paypal.com/cgi-bin/webscr");  
	    //正式环境  
	    //      URL u = new URL("https://www.paypal.com/cgi-bin/webscr");  
	    URLConnection uc = u.openConnection();  
	    uc.setDoOutput(true);  
	    uc.setRequestProperty("Content-Type",  
	            "application/x-www-form-urlencoded");  
	    PrintWriter pw = new PrintWriter(uc.getOutputStream());  
	    pw.println(str);  
	    pw.close();  
	    //接受 PayPal 对 IPN 回发的回复信息  
	    BufferedReader in = new BufferedReader(new InputStreamReader(  
	            uc.getInputStream()));  
	    String res = in.readLine();  
	    in.close();  
	  
	    //将 POST 信息分配给本地变量，可以根据您的需要添加  
	    //该付款明细所有变量可参考：  
	    //https://www.paypal.com/IntegrationCenter/ic_ipn-pdt-variable-reference.html  
	    String itemName = request.getParameter("item_name");//商品名  
	    String itemNumber = request.getParameter("item_number");//购买数量  
	    String paymentStatus = request.getParameter("payment_status");//交易状态  
	    String paymentDate = request.getParameter("payment_date");//交易时间  
	    String paymentAmount = request.getParameter("mc_gross");//交易钱数  
	    String paymentCurrency = request.getParameter("mc_currency");//货币种类  
	    String txnId = request.getParameter("txn_id");//交易id  
	    String receiverEmail = request.getParameter("receiver_email");//收款人email  
	    String payerEmail = request.getParameter("payer_email");//付款人email  
	  
	    if (res == null || res == "")  
	        res = "0";  
	    //…  
	    //获取 PayPal 对回发信息的回复信息，判断刚才的通知是否为 PayPal 发出的  
	    if (res.equals("VERIFIED")) {  
	        //检查付款状态  
	        //检查 txn_id 是否已经处理过  
	        //检查 receiver_email 是否是您的 PayPal 账户中的 EMAIL 地址  
	        //检查付款金额和货币单位是否正确  
	        //处理其他数据，包括写数据库  
	          System.out.println("################");
	          System.out.println(res);
	          return "Completed".equals(paymentStatus);  
	    } else if (res.equals("INVALID")) {  
	        //非法信息，可以将此记录到您的日志文件中以备调查  
	    	System.out.println("################");
	          System.out.println(res);
	    } else {  
	        //处理其他错误  
	    	System.out.println("################");
	          System.out.println(res);
	    }
		return false;  
	}
}
